package com.alibaba.nacos.naming.core.v2.event.publisher;

import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.EventPublisher;
import com.alibaba.nacos.common.notify.EventPublisherFactory;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class NamingEventPublisherFactory
        implements EventPublisherFactory {

    public final static NamingEventPublisherFactory INSTANCE = new NamingEventPublisherFactory();
    private final Map<Class<? extends Event>, NamingEventPublisher> publisher = new ConcurrentHashMap<>();

    @Override
    public EventPublisher apply(Class<? extends Event> eventType,
                                Integer maxQueueSize) {
        Class<? extends Event> usingEventType = eventType.isMemberClass() ? (Class<? extends Event>) eventType.getEnclosingClass() : eventType;
        return publisher.computeIfAbsent(usingEventType, clazz -> {
            NamingEventPublisher namingEventPublisher = new NamingEventPublisher();
            namingEventPublisher.init(clazz, maxQueueSize);
            return namingEventPublisher;
        });
    }
}

